using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using WPF_MVVM_Test.MVVM_Model.Material;

namespace WPF_MVVM_Test.MVVM_View.Material
{
    /// <summary>
    /// TreeComboBox.xaml 的交互逻辑
    /// </summary>
    public partial class TreeComboBox : System.Windows.Controls.UserControl
    {
        public static readonly DependencyProperty ItemsSourceProperty =
            DependencyProperty.Register("ItemsSource", typeof(ObservableCollection<MaterialCategory>), 
                typeof(TreeComboBox), new PropertyMetadata(null, OnItemsSourceChanged));

        public static readonly DependencyProperty SelectedValueProperty =
            DependencyProperty.Register("SelectedValue", typeof(string), 
                typeof(TreeComboBox), new FrameworkPropertyMetadata(null, 
                    FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedValueChanged));

        public static readonly DependencyProperty HintTextProperty =
            DependencyProperty.Register("HintText", typeof(string), 
                typeof(TreeComboBox), new PropertyMetadata("请选择分类"));

        public TreeComboBox()
        {
            InitializeComponent();
            this.Loaded += TreeComboBox_Loaded;
        }

        private void TreeComboBox_Loaded(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("TreeComboBox_Loaded called");
            UpdateComboBoxItems();
        }

        public ObservableCollection<MaterialCategory> ItemsSource
        {
            get { return (ObservableCollection<MaterialCategory>)GetValue(ItemsSourceProperty); }
            set { SetValue(ItemsSourceProperty, value); }
        }

        public string SelectedValue
        {
            get { return (string)GetValue(SelectedValueProperty); }
            set { SetValue(SelectedValueProperty, value); }
        }

        public string HintText
        {
            get { return (string)GetValue(HintTextProperty); }
            set { SetValue(HintTextProperty, value); }
        }

        private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is TreeComboBox control)
            {
                System.Diagnostics.Debug.WriteLine("OnItemsSourceChanged triggered");
                control.UpdateComboBoxItems();
            }
        }

        private static void OnSelectedValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is TreeComboBox control)
            {
                control.UpdateSelectedItem();
            }
        }

        private void UpdateComboBoxItems()
        {
            System.Diagnostics.Debug.WriteLine($"UpdateComboBoxItems called, ItemsSource is null: {ItemsSource == null}");
            
            if (ItemsSource == null || ItemsSource.Count == 0)
            {
                System.Diagnostics.Debug.WriteLine("ItemsSource is null or empty, clearing ComboBox");
                CategoryComboBox.ItemsSource = null;
                return;
            }

            System.Diagnostics.Debug.WriteLine($"ItemsSource count: {ItemsSource.Count}");
            
            try
            {
                var flatItems = GetFlattenedItems(ItemsSource.ToList());
                System.Diagnostics.Debug.WriteLine($"Flattened items count: {flatItems.Count}");
                
                // 先清空再设置
                CategoryComboBox.ItemsSource = null;
                CategoryComboBox.ItemsSource = flatItems;
                CategoryComboBox.SelectedValuePath = "Id";
                
                foreach (var item in flatItems)
                {
                    System.Diagnostics.Debug.WriteLine($"Flat item: {item.CategoryName} (Level: {item.Level})");
                }
                
                System.Diagnostics.Debug.WriteLine("ComboBox ItemsSource updated successfully");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Error in UpdateComboBoxItems: {ex.Message}");
            }
        }

        private void UpdateSelectedItem()
        {
            if (CategoryComboBox.ItemsSource != null)
            {
                CategoryComboBox.SelectedValue = SelectedValue;
            }
        }

        private List<MaterialCategory> GetFlattenedItems(List<MaterialCategory> categories, int level = 0)
        {
            var result = new List<MaterialCategory>();
            
            foreach (var category in categories)
            {
                // 设置层级
                category.Level = level;
                result.Add(category);
                
                // 递归处理子节点
                if (category.Children != null && category.Children.Count > 0)
                {
                    result.AddRange(GetFlattenedItems(category.Children, level + 1));
                }
            }
            
            return result;
        }

        private void CategoryComboBox_DropDownOpened(object sender, EventArgs e)
        {
            // 下拉框打开时的处理逻辑
        }

        private void CategoryComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (CategoryComboBox.SelectedValue != null && CategoryComboBox.SelectedValue.ToString() != SelectedValue)
            {
                SelectedValue = CategoryComboBox.SelectedValue.ToString();
            }
        }

        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);
            CategoryComboBox.SelectionChanged += CategoryComboBox_SelectionChanged;
        }
    }

    /// <summary>
    /// 层级到边距转换器
    /// </summary>
    public class LevelToMarginConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is int level)
            {
                return new Thickness(level * 20, 0, 0, 0);
            }
            return new Thickness(0);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    /// <summary>
    /// 层级到可见性转换器
    /// </summary>
    public class LevelToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is int level && level > 0)
            {
                return Visibility.Visible;
            }
            return Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}